from models import SimpleComment
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.conf import settings
import sha

class RelatedComments:
    def __init__(self, model):
        self.model = model
        self.content_type = ContentType.objects.get_for_model(model)

    def count(self):
        comment_count = SimpleComment.objects.filter(object_id__exact=self.model.id,
            content_type__app_label__exact=self.content_type.app_label,
            content_type__model__exact=self.content_type.model).count()
        return comment_count
    
    def list(self):
        comment_list = SimpleComment.objects.filter(object_id__exact=self.model.id,
            content_type__app_label__exact=self.content_type.app_label,
            content_type__model__exact=self.content_type.model,)
        return comment_list


# Captcha class handles creation and validation of Captcha images
# Submitted form must contain a "key" and "hash" field for validation
class Captcha:
    def __init__(self, POST=''):
        self.image_root =       settings.SIMPLECOMMENT_IMAGE_ROOT
        self.image_url_prefix = settings.SIMPLECOMMENT_IMAGE_URL
        self.font =             settings.SIMPLECOMMENT_FONT_FILE
        self.bg =               settings.SIMPLECOMMENT_BG_IMAGE
        self.font_size = 48
        self.font_color = 128
        self.salt = settings.SECRET_KEY
        if not POST:
            self.generate_image()
        else :
            self.hash = POST.get('hash', '')
            self.key = POST.get('key', '')
            if self.hash and self.key:
                self.image = self.image = self.image_url_prefix + self.hash + '.png'
            else:
                self.generate_image
    
    def generate_image(self):
        from random import choice
        import Image, ImageDraw, ImageFont
        
        image_text = ''.join([choice('ABCDEFGHJKLMNPQRSTUV') for i in range(5)])
        image_hash = sha.new(self.salt+image_text).hexdigest()
        self.hash = image_hash
        
        image=Image.open(self.bg)
        draw=ImageDraw.Draw(image)
        font=ImageFont.truetype(self.font, self.font_size)
        draw.text((11,1), image_text, font=font, fill=0)
        image_name = image_hash + '.png'
        image_path = self.image_root + image_name
        image.save(image_path, "PNG")
        self.image = self.image_url_prefix + image_name 
        return self.image_url_prefix + image_name
    
    def image(self):
        if self.image:
            return self.image
        else:
            return ''

    def hash(self):
        if self.hash:
            return self.hash
        else:
            return ''
    
    def is_valid(self):
        if self.hash and self.key:
            if sha.new(self.salt+self.key.upper()).hexdigest() == self.hash:
                return True
            else:
                return False
        else:
            return False
